<template>
	<view>
		<custom-navigation-bar title="添加活动"></custom-navigation-bar>
		<view class="main">
			<view class="form-item">
				<view class="form-item-1">
					<view class="form-item-lable">
						活动名称
					</view>
					<view class="form-item-countent">
						<input type="text" class="form-item-input" placeholder="请输入活动名称" @input="updateActivityName" />
					</view>
					<view class="form-item-right">
						<image src="/static/gengduo@3x(1).png" class="form-item-image"></image>
					</view>
				</view>
			</view>
			<view class="form-item">
				<view class="form-item-1">
					<view class="form-item-lable">
						类型
					</view>
					<view class="form-item-countent">
						<picker model='selector' @change="updateActivityType" :range="typeArr" range-key="name">
							<input type="text" class="picker" :value="type" placeholder="请选择活动类型" />
						</picker>
					</view>
					<view class="form-item-right">
						<image src="/static/gengduo@3x(1).png" class="form-item-image"></image>
					</view>
				</view>
			</view>
			<view class="form-item">
				<view class="form-item-1" style="border: none;">
					<view v-for="(item,index) in money" :key="index">
						<view class="form-item-lable">
							<text v-if="index==0" style="margin-top: 20rpx;">费用</text>
							<text v-if="index>0">&nbsp;</text>
						</view>
						<view class="form-item-countent1">
							<input placeholder="请输入标题" class="feiyong-title" @focus='getMoneyIndex(index)'
								@input="moneyTypeInput" />
							<image v-if="index==0" src="/static/add.png" @focus='getMoneyIndex(index)'
								class="form-item-image-1" @click="addMoney()"></image>
							<image v-if="index !=0 && index==money.length-1" src="/static/sub.png"
								@focus='getMoneyIndex(index)' class="form-item-image-1" @click="subMoney(index)">
							</image>
							<input placeholder="请输入费用" class="feiyong-money" @focus='getMoneyIndex(index)'
								@input="moneyInput" />
						</view>
					</view>
					<view class="ta_01"></view>
				</view>
			</view>
			<view class="form-item">
				<view class="form-item-1">
					<view class="form-item-lable">
						分佣比例
					</view>
					<view class="form-item-countent">
						<input type="text" class="form-item-input" placeholder="请输入分佣比例" @input="updateActivityRatio" />
					</view>
					<view class="form-item-right">
						<image src="/static/gengduo@3x(1).png" class="form-item-image"></image>
					</view>
				</view>
			</view>
			<view class="form-item">
				<view class="form-item-1">
					<view class="form-item-lable">
						人数上限
					</view>
					<view class="form-item-countent">
						<input type="text" class="form-item-input" placeholder="请输入人数上限" @input="updateMaxNum" />
					</view>
					<view class="form-item-right">
						<image src="/static/gengduo@3x(1).png" class="form-item-image"></image>
					</view>
				</view>
			</view>
			<view class="form-item">
				<view class="form-item-1">
					<view class="form-item-lable">
						截止时间
					</view>
					<view class="form-item-countent">
						<picker mode='date' @change="signEndTimeChange">
							<input type="text" class="picker" :value="signEndTimeData" placeholder="请选择报名截止时间" />
						</picker>
					</view>
					<view class="form-item-right">
						<image src="/static/gengduo@3x(1).png" class="form-item-image"></image>
					</view>
				</view>
			</view>
			<view class="form-item">
				<view class="form-item-1">
					<view class="form-item-lable">
						活动时间
					</view>
					<view class="form-item-countent">
						<picker mode='date' @change="activityBeginTimeChange">
							<input type="text" class="picker" :value="activityBeginTimeData" placeholder="请选择活动时间" />
						</picker>
					</view>
					<view class="form-item-right">
						<image src="/static/gengduo@3x(1).png" class="form-item-image"></image>
					</view>
				</view>
			</view>

			<view class="form-item">
				<view class="form-item-1">
					<view class="form-item-lable">
						范围
					</view>
					<view class="form-item-countent">
						<picker model='selector' @change="activityRegionChange" :range="regionArr" range-key="name">
							<input type="text" class="picker" :value="region" placeholder="请选择活动所在区" />
						</picker>
					</view>
					<view class="form-item-right">
						<image src="/static/gengduo@3x(1).png" class="form-item-image"></image>
					</view>
				</view>
			</view>
			<view class="form-item">
				<view class="form-item-1">
					<view class="form-item-lable">
						活动详细地址
					</view>
					<view class="form-item-countent">
						<input type="text" class="form-item-input" placeholder="请输入活动地址"
							@input="updateActivityPosition" />
					</view>
					<view class="form-item-right">
						<image src="/static/gengduo@3x(1).png" class="form-item-image"></image>
					</view>
				</view>
			</view>
			<view class="form-item">
				<view style="width: 84%;float: left;margin-left: 8%;">
					<uni-file-picker limit="1" title="活动缩略图" @select="handleMiniImageSelect"
						@delete="handleMiniImageDelete"></uni-file-picker>
					<view class="ta_01"></view>
				</view>
			</view>
			<view class="form-item">
				<view class="upload_01">
					<uni-file-picker limit="5" title="活动主图" @select="handleMainImageSelect"
						@delete="handleMainImageDelete"></uni-file-picker>
					<view class="ta_01"></view>
				</view>
			</view>
			<view class="form-item">
				<view class="upload_01">
					<view class="a_title">
						活动详情
					</view>
					<view v-for="(item,index) in activityDetail" :key="index">
						<view class="b_content">
							<input placeholder="请输入主标题" class="c_ttt" @focus="setActivityDetailIndex(index)"
								@input="activityDetailTitleInput" />
							<view v-for="(item1,index1) in item.detail" :key="index1">
								<view class="b-1-2">
									<input placeholder="请输入标题" class="d_ttt"
										@focus="setActivityDetailContentIndex(index,index1)"
										@input="activityDetailContentTitleInput" />
									<input placeholder="请输入内容" class="g_ttt"
										@focus="setActivityDetailContentIndex(index,index1)"
										@input="activityDetailContentContentInput" />
									<image v-if="index1==0" src="/static/add.png" class="form-item-image-1"
										@click="addActivityDetailContent(index)"></image>
									<image v-if="index1 > 0 && index1==item.detail.length-1" src="/static/sub.png"
										class="form-item-image-1" @click="subActivityDetailContent(index,index1)">
									</image>
								</view>
							</view>
						</view>
						<view class="b-1-1">
							<image v-if="index==0" src="/static/add.png" class="form-item-image-1"
								@click="addActivityDetail()"></image>
							<image v-if="index > 0 && index==activityDetail.length-1" src="/static/sub.png"
								class="form-item-image-1" @click="subActivityDetail(index)"></image>
						</view>
					</view>
				</view>
				<view class="ta_02" style="height: 20rpx;"></view>
			</view>
			<view class="form-item">
				<view class="upload_01">
					<uni-file-picker limit="5" title="图文详情" @select="handleDetailImageSelect"
					@delete="handleDetailImageDelete"></uni-file-picker>
					<view class="ta_01"></view>
				</view>
			</view>
			<view class="form-item">
				<view class="upload_01">
					<view class="a_title">
						购买须知
					</view>
					<view v-for="(item,index) in buyNotice" :key="index">
						<view class="b_content">
							<input placeholder="请输入主标题" class="c_ttt" @focus="setBuyNoticeIndex(index)"
								@input="buyNoticeTitleInput" />
							<view v-for="(item1,index1) in item.detail" :key="index1">
								<view class="b-1-2">
									<input placeholder="请输入内容" class="z_ttt"
										@focus="setBuyNoticeDetailIndex(index,index1)" @input="buyNoticeContentInput" />
									<image v-if="index1==0" src="/static/add.png" class="form-item-image-1"
										@click="addBuyNoticeContent(index)"></image>
									<image v-if="index1 > 0 && index1==item.detail.length-1" src="/static/sub.png"
										class="form-item-image-1" @click="subBuyNoticeContent(index,index1)"></image>
								</view>
							</view>
						</view>
						<view class="b-1-1">
							<image v-if="index==0" src="/static/add.png" class="form-item-image-1"
								@click="addBuyNotice()"></image>
							<image v-if="index>0 && index==buyNotice.length-1" src="/static/sub.png"
								class="form-item-image-1" @click="subBuyNotice(index)"></image>
						</view>
					</view>
				</view>
				<view class="ta_02" style="height: 20rpx;"></view>
			</view>
		</view>
		<view class="form-item">
			<view class="btn-b1">
				<view class="btn" @click="submit">提交</view>
			</view>
		</view>
		<view class="btn-0010"></view>
	</view>
</template>

<script setup>
	import CustomNavigationBar from '@/components/CustomNavigationBar.vue';
	import http from '../../../utils/http';
	import {
		getCurrentInstance
	} from "vue";
	import {
		generateApplicationId,
		getCurrentTimestamp,
		generateTime
	} from '../../../utils/timeUtils';
	const {
		ctx: that,
		proxy
	} = getCurrentInstance()
	const activity = ref({
		activityId: "",
		activityName: "",
		activityType: "",
		signBeginTime: "",
		signEndTime: "",
		activityBeginTime: "",
		activityEndTime: "",
		activityRatio: 1.0,
		activityRegion: "",
		activityPosition: "",
		activityCommunity: "",
		activityMiniImage: "",
		activityMainImage: [],
		minPrice: "",
		maxPrice: "",
		currentNum: 0,
		maxNum: 0,
		activityDetail: [],
		activityDetailImage: [],
		money: [],
		buyNotice: [],
		applicationStatus: "normal",
		applicationTime: ""

	})
	// 类型
	const type = ref('');
	const typeIndex = ref(0);
	const typeArr = ref([{
			id: 1,
			name: '公益活动'
		},
		{
			id: 2,
			name: '社区活动'
		}
	]);
	// 范围
	const region = ref('');
	const regionIndex = ref(0);
	const regionArr = ref([{
			id: 1,
			name: '全国'
		},
		{
			id: 2,
			name: '本省'
		},
		{
			id: 3,
			name: '本市'
		},
		{
			id: 4,
			name: '本小区'
		}
	]);



	function typeChange(e) {
		const index = e.detail.value;
		type.value = typeArr.value[index].name;
		typeIndex.value = typeArr.value[index].id;
	}

	function updateActivityName(e) {
		activity.value.activityName = e.target.value;
	}

	function updateActivityType(e) {
		const index = e.detail.value;
		type.value = typeArr.value[index].name;
		typeIndex.value = typeArr.value[index].id;
		activity.value.activityType = type.value;
	}

	function updateActivityRatio(e) {
		activity.value.activityRatio = e.target.value;
	}

	function updateMaxNum(e) {
		activity.value.maxNum = e.target.value;
	}
	// 报名截止时间
	const signEndTimeData = ref('');

	function signEndTimeChange(e) {
		signEndTimeData.value = e.detail.value;
		activity.value.signEndTime = e.detail.value;
	}
	// 活动开始时间
	const activityBeginTimeData = ref('');

	function activityBeginTimeChange(e) {
		activityBeginTimeData.value = e.detail.value;
		activity.value.activityBeginTime = e.detail.value;
	}

	function activityRegionChange(e) {
		const index = e.detail.value;
		region.value = regionArr.value[index].name;
		regionIndex.value = regionArr.value[index].id;
		activity.value.activityRegion = region.value;
	}

	function updateActivityPosition(e) {
		activity.value.activityPosition = e.target.value;
	}
	const image = ref({
		miniImage: "", // 缩略图
		mainImage: [], // 主图
		detailImage: [] // 详情图
	})
	// 缩略图
	function handleMiniImageSelect(e) {
		image.value.miniImage = e.tempFiles
	}

	function handleMiniImageDelete(e) {
		image.value.miniImage = e.tempFiles
	}
	// 主图
	function handleMainImageSelect(e) {
		if (e.tempFiles.length == 0) {
			return;
		}
		for (let i in e.tempFiles) {
			image.value.mainImage.push(e.tempFiles[i])
		}

	}

	function handleMainImageDelete(e) {
		console.log("delete", e)
		image.value.mainImage.splice(e.index, 1); // 移除数组中对应的文件
	}
	// 详情图
	function handleDetailImageSelect(e) {
		if (e.tempFiles.length == 0) {
			return;
		}
		for (let i in e.tempFiles) {
			image.value.detailImage.push(e.tempFiles[i])
		}
	}

	function handleDetailImageDelete(e) {
		console.log("delete", e)
		image.value.detailImage.splice(e.index, 1); // 移除数组中对应的文件
	}
	//----------------------------------费用开始------------------------------
	const moneyIndex = ref(0);
	//获取当前输入框的索引
	function getMoneyIndex(index) {
		moneyIndex.value = index;
	}
	const money = ref([{
		id: 0,
		type: '',
		money: ''
	}]);
	//添加
	function addMoney() {
		money.value.push({
			type: '',
			money: ''
		});
		console.log(money.value);
		activity.value.money = money.value
	}
	//删除
	function subMoney(index) {
		money.value.splice(index, 1);
		console.log(money.value);
		activity.value.money = money.value
	}
	//标题输入
	function moneyTypeInput(event) {
		console.log(event.target.value)
		money.value[moneyIndex.value].type = event.target.value;
		activity.value.money = money.value
	}
	//钱数输入
	function moneyInput(event) {
		money.value[moneyIndex.value].money = event.target.value
		activity.value.money = money.value
	}
	//----------------------------------费用结束------------------------------

	//----------------------------------活动详情开始--------------------------
	//详情输入框的索引
	const activityDetailIndex = ref(0);
	//获取详情输入框的索引
	function setActivityDetailIndex(index) {
		activityDetailIndex.value = index;
	}
	const activityDetail = ref([{
		title: '',
		detail: [{
			title: '',
			content: ''
		}]
	}]);
	//添加一级标题内容
	function addActivityDetail() {
		activityDetail.value.push({
			title: '',
			detail: [{
				title: '',
				content: ''
			}]
		});
		console.log(activityDetail.value);
		activity.value.activityDetail = activityDetail.value
	}
	//删除一级标题内容
	function subActivityDetail(index) {
		activityDetail.value.splice(index, 1);
		activity.value.activityDetail = activityDetail.value
	}
	//一级标题输入
	function activityDetailTitleInput(event) {
		activityDetail.value[activityDetailIndex.value].title = event.target.value
		activity.value.activityDetail = activityDetail.value
	}
	//添加二级标题
	function addActivityDetailContent(index) {
		activityDetail.value[index].detail.push({
			title: '',
			content: ''
		});
		activity.value.activityDetail = activityDetail.value
	}
	//删除二级标题
	function subActivityDetailContent(index, index1) {
		activityDetail.value[index].detail.splice(index1, 1);
		activity.value.activityDetail = activityDetail.value
	}
	//二级标题索引
	const activityDetailContentIndex = ref([0, 0]);

	function setActivityDetailContentIndex(index, index1) {
		activityDetailContentIndex.value = [index, index1];
	}
	//二级标题输入
	function activityDetailContentTitleInput(event) {
		activityDetail.value[activityDetailContentIndex.value[0]].detail[activityDetailContentIndex.value[1]].title = event
			.target.value;
		activity.value.activityDetail = activityDetail.value
	}
	//二级标题内容输入
	function activityDetailContentContentInput(event) {
		activityDetail.value[activityDetailContentIndex.value[0]].detail[activityDetailContentIndex.value[1]].content =
			event.target.value;
		activity.value.activityDetail = activityDetail.value
	}
	//----------------------------------活动详情结束--------------------------
	//----------------------------------购买须知开始--------------------------
	//购买须知索引
	const buyNoticeIndex = ref(0);

	function setBuyNoticeIndex(index) {
		buyNoticeIndex.value = index;
		console.log(buyNoticeIndex.value)
	}
	const buyNotice = ref([{
		title: '',
		detail: [{
			content: ''
		}]
	}]);
	//添加一级标题
	function addBuyNotice() {
		buyNotice.value.push({
			title: '',
			detail: [{
				content: ''
			}]
		});
		console.log(buyNotice.value)
		activity.value.buyNotice = buyNotice.value
	}
	//删除一级标题
	function subBuyNotice(index) {
		buyNotice.value.splice(index, 1);
	}
	//一级标题内容输入
	function buyNoticeTitleInput(event) {
		console.log(event.target.value + '-----' + buyNoticeIndex.value)
		buyNotice.value[buyNoticeIndex.value].title = event.target.value;
		activity.value.buyNotice = buyNotice.value
	}
	//二级标题索引
	const buyNoticeDetailIndex = ref([0, 0]);
	//设置二级标题索引
	function setBuyNoticeDetailIndex(index, index1) {
		buyNoticeDetailIndex.value = [index, index1];
	}
	//添加二级内容
	function addBuyNoticeContent(index) {
		buyNotice.value[index].detail.push({
			content: ''
		});
		activity.value.buyNotice = buyNotice.value
	}
	//删除二级内容
	function subBuyNoticeContent(index, index1) {
		buyNotice.value[index].detail.splice(index1, 1);
		activity.value.buyNotice = buyNotice.value
	}
	//二级内容输入
	function buyNoticeContentInput(event) {
		buyNotice.value[buyNoticeDetailIndex.value[0]].detail[buyNoticeDetailIndex.value[1]].content = event.target.value;
		activity.value.buyNotice = buyNotice.value
	}
	//---------------------------------购买须知结束---------------------------
// 上传文件函数
	async function uploadFile(file, fileType) {
		console.log("uploda diaoyong")
		return new Promise((resolve, reject) => {
			uni.uploadFile({
				url: 'http://localhost:8080/utils/upLoadCommodityImage',
				filePath: file.path,
				name: 'file', // 文件字段名
				formData: {
					"filename": generateApplicationId(true, file),
					"activityId": activity.value.activityId,
					"type": "Commodity"
				},
				success: (uploadRes) => {
					console.log("成功")
					const res = JSON.parse(uploadRes.data).data;
					if (fileType === 'mainImage') {
						activity.value.activityMainImage.push(res)
					} else if (fileType === 'miniImage') {
						activity.value.activityMiniImage = res;
					} else if (fileType === 'detailImage') {
						activity.value.activityDetailImage.push(res);
					}
					resolve();
				},
				fail: (error) => {
					console.log('上传失败', error);
					reject(error);
				}
			});
		});
	}
	async function submit() {
		try {
			activity.value.activityId = generateApplicationId(false);
			activity.value.applicationTime = generateTime();
			console.log("activity", activity.value);
			
			// 上传主图
			const mainImagePromises = image.value.mainImage.map(mainImageFile => uploadFile(mainImageFile, 'mainImage'));
			
			// 上传缩略图
			let miniImagePromise = Promise.resolve();
			if (image.value.miniImage) {
				console.log("上传营业执照");
				miniImagePromise = uploadFile(image.value.miniImage[0], 'miniImage');
			}
			
			// 上传详情图
			const detailImagePromises = image.value.detailImage.map(detailImage => uploadFile(detailImage, 'detailImage'));
			
			// 等待所有上传操作完成
			await Promise.all([...mainImagePromises, miniImagePromise, ...detailImagePromises]);
			
			// 所有上传操作完成后，调用 http.request
			const responseData = await http.request({
				url: "/api/cityPartner/add_activity",
				method: "POST",
				data: {
					"activity": activity.value
				}
			});
			console.log("提交成功", responseData.data);
			uni.showToast({
				icon: "success",
				title: "提交成功",
				duration: 1500,
				complete: function() {
					setTimeout(function() {
						uni.navigateBack({
							delta: 1 // 返回到上一页
						});
					}, 1500); // 延迟 1.5 秒，和 showToast 的 duration 相同
				}
			})
		} catch (err) {
			// 在这里处理上传文件过程中的错误
			console.log("上传文件失败", err);
		}
	}
</script>

<style>
	@import "../../application/form.scss";
</style>